﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Common
{
    public static class EmailHelper
    {
        // Fields
        private static Regex mailRegex = new Regex("\\A(?:(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\]))\\Z");

        // Methods
        public static void Send(string from, string title, string body, string displayName, string smtp = "mail.itv.cn", string smtpUsername = "lichun@itv.cn", string smtpPassword = "!QAZ2wsx", bool isAysnc = false, params string[] tos)
        {
            MailAddress address = new MailAddress(from, displayName, Encoding.UTF8);
            MailMessage message = new MailMessage
            {
                From = address,
                Body = body,
                Subject = title,
                BodyEncoding = Encoding.UTF8,
                Priority = MailPriority.High,
                IsBodyHtml = true
            };
            foreach (string str in tos)
            {
                if (mailRegex.IsMatch(str))
                {
                    message.Bcc.Add(str);
                }
            }
            SmtpClient client = new SmtpClient(smtp)
            {
                Credentials = new NetworkCredential(smtpUsername, smtpPassword),
                DeliveryMethod = SmtpDeliveryMethod.Network
            };
            if (isAysnc)
            {
                client.SendAsync(message, null);
            }
            else
            {
                client.Send(message);
            }
        }
    }


}
